// src/utils/upload.ts
import axios from 'axios';
import { message } from 'antd';

// /​**​
//  * 通用文件上传函数
//  * @param file 文件对象
//  * @param uploadUrl 上传接口URL（支持相对路径）
//  * @param extraParams 额外业务参数（如 { userId: '123' }）
//  * @param onSuccess 上传成功回调（接收文件URL）
//  * @param onError 上传失败回调（接收错误信息）
//  */
export const uploadFile = async (
  file: File,
  extraParams: Record<string, any> = {},
  onSuccess?: (url: string) => void,
  onError?: (error: Error) => void
): Promise<void> => {
  const formData = new FormData();
  formData.append('file', file); // 后端接收文件的字段名
  const uploadUrl = "/admin-api/infra/file/upload"
  // 附加业务参数
  Object.keys(extraParams).forEach(key => {
    formData.append(key, extraParams[key]);
  });

  try {
    const response = await axios.post(uploadUrl, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        // Authorization: `Bearer ${localStorage.getItem('token')}`, // 可选认证
      },
    });

    if (response.data?.url) {
      onSuccess?.(response.data.url); // 触发成功回调
    } else {
      throw new Error('上传失败：未返回文件URL');
    }
  } catch (error) {
    onError?.(error instanceof Error ? error : new Error('上传失败'));
  }
};



export const uploadImageFile = async (
  file: File,
  extraParams: Record<string, any> = {},
  onSuccess?: (url: string) => void,
  onError?: (error: Error) => void
): Promise<void> => {
  const formData = new FormData();
  formData.append('file', file); // 后端接收文件的字段名
 const uploadUrl = "/admin-api/infra/file/image/upload"
  // 附加业务参数
  Object.keys(extraParams).forEach(key => {
    formData.append(key, extraParams[key]);
  });

  try {
    const response = await axios.post(uploadUrl, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        // Authorization: `Bearer ${localStorage.getItem('token')}`, // 可选认证
      },
    });

    if (response.data?.url) {
      onSuccess?.(response.data.url); // 触发成功回调
    } else {
      throw new Error('上传失败：未返回文件URL');
    }
  } catch (error) {
    onError?.(error instanceof Error ? error : new Error('上传失败'));
  }
};


export const downloadTruckBol = async (id: string, fileName: string) => {
  try {
    const downloadUrl = `/admin-api/system/truck-order/bol/download/${id}`;
    
    // 使用 axios 请求
    const response = await axios.get(downloadUrl, {
      responseType: 'blob', // 重要：指定响应类型为 blob
    });
    

    // 从响应头获取文件名
    const contentDisposition = response.headers['content-disposition'];
    let downloadFileName = fileName;
    
    if (contentDisposition) {
      const fileNameMatch = contentDisposition.match(
        /filename="([^"]+)"|filename=([^;]+)/
      );
      if (fileNameMatch) {
        // 优先取引号内的内容（第1组），否则取无引号的内容（第2组）
        downloadFileName = decodeURIComponent(
          fileNameMatch[1] || fileNameMatch[2]
        );
      }
    }
    // console.log("filename:"+downloadFileName)
    // 创建下载链接
    const blob = new Blob([response.data]);
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = downloadFileName;
    document.body.appendChild(link);
    link.click();
    
    // 清理
    setTimeout(() => {
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
    }, 100);

    message.success('文件下载成功');
  } catch (error) {
    console.error('下载错误:', error);
    message.error('文件下载失败');
  }
};